<?php defined("MAIN_DIR") or die("No direct access");

$deposit_id = UV::readInt($route->getPath(4));

$edit_error = false;
$count_error = false;
if (isset($_POST['action']) && $_POST['action'] == "edit")
{
	$rub_count = $usd_count = $eur_count = 0;
	if (isset($_POST['rub']))
	{
		$rub_percents = array();
		for ($i=1; $i <= $_POST['rub_amounts']; $i++)
		{
			for ($j=1; $j <= $_POST['rub_periods']; $j++)
			{
				$rub_percents[$rub_count]['percent'] = $_POST['rub_percent_'.$j.'_'.$i];
				$rub_percents[$rub_count]['period'] = $_POST['rub_period_'.$j];
				$rub_percents[$rub_count++]['amount'] = $_POST['rub_amount_'.$i];
			}
		}
	}
	if (isset($_POST['usd']))
	{
		$usd_percents = array();
		for ($i=1; $i <= $_POST['usd_amounts']; $i++)
		{
			for ($j=1; $j <= $_POST['usd_periods']; $j++)
			{
				$usd_percents[$usd_count]['percent'] = $_POST['usd_percent_'.$j.'_'.$i];
				$usd_percents[$usd_count]['period'] = $_POST['usd_period_'.$j];
				$usd_percents[$usd_count++]['amount'] = $_POST['usd_amount_'.$i];
			}
		}
	}
	if (isset($_POST['eur']))
	{
		$eur_percents = array();
		for ($i=1; $i <= $_POST['eur_amounts']; $i++)
		{
			for ($j=1; $j <= $_POST['eur_periods']; $j++)
			{
				$eur_percents[$eur_count]['percent'] = $_POST['eur_percent_'.$j.'_'.$i];
				$eur_percents[$eur_count]['period'] = $_POST['eur_period_'.$j];
				$eur_percents[$eur_count++]['amount'] = $_POST['eur_amount_'.$i];
			}
		}
	}
	
	$name = trim(filter_var($_POST['name'],FILTER_SANITIZE_MAGIC_QUOTES));
	$bank = filter_var($_POST['bank'],FILTER_SANITIZE_MAGIC_QUOTES);
	$regionally = $route->POST("regionally") ? 1 : 0;
	if ($db->getCell("select `parent` from `bank` where `bank_id` = '$bank' limit 1")) {
		$regionally = 0;
	}
	$increase = isset($_POST['increase']) ? 1 : 0;
	$partial_taking = isset($_POST['partial_taking']) ? 1 : 0;
	$procent_charge = trim(filter_var($_POST['procent_charge'],FILTER_SANITIZE_MAGIC_QUOTES));
	
	$edit_query = "update `deposit` set `bank_id`='$bank',`regionally`='$regionally',`name`='$name',`increase`='$increase',`partial_taking`='$partial_taking',`procent_charge`='$procent_charge' where `deposit_id` = '$_POST[deposit_id]' limit 1";
	if ($rub_count == 0 && $usd_count == 0 && $eur_count == 0)
		$count_error = true;
	if (!$count_error && mysql_query($edit_query))
	{
		mysql_query("delete from `deposit_percent` where `deposit_id` = '$_POST[deposit_id]'");
		$dp_query = "";
		if ($rub_count > 0)
		{
			$dp_query = "insert into `deposit_percent` (`deposit_id`,`period`,`amount`,`currency`,`percent`) values ";
			for ($i = 0; $i < $rub_count; $i++)
			{
				$dp_query .= "('$_POST[deposit_id]','".$rub_percents[$i]['period']."','".$rub_percents[$i]['amount']."','RUB','".$rub_percents[$i]['percent']."')";
				if ($i < $rub_count-1)
					$dp_query .= ",";
			}
		}
		if ($usd_count > 0)
		{
			if ($dp_query == "")
				$dp_query = "insert into `deposit_percent` (`deposit_id`,`period`,`amount`,`currency`,`percent`) values ";
			else
				$dp_query .= ",";
			for ($i = 0; $i < $usd_count; $i++)
			{
				$dp_query .= "('$_POST[deposit_id]','".$usd_percents[$i]['period']."','".$usd_percents[$i]['amount']."','USD','".$usd_percents[$i]['percent']."')";
				if ($i < $usd_count-1)
					$dp_query .= ",";
			}
		}
		if ($eur_count > 0)
		{
			if ($dp_query == "")
				$dp_query = "insert into `deposit_percent` (`deposit_id`,`period`,`amount`,`currency`,`percent`) values ";
			else
				$dp_query .= ",";
			for ($i = 0; $i < $eur_count; $i++)
			{
				$dp_query .= "('$_POST[deposit_id]','".$eur_percents[$i]['period']."','".$eur_percents[$i]['amount']."','EUR','".$eur_percents[$i]['percent']."')";
				if ($i < $eur_count-1)
					$dp_query .= ",";
			}
		}
		
		if ($dp_query != "")
			mysql_query($dp_query);
	}
	else
		$edit_error = true;
}
if ($deposit_id) {
	$deposit_res = mysql_query("select * from `deposit` where `deposit_id` = '$deposit_id' limit 1");
	if (mysql_num_rows($deposit_res) == 0) {
		to("/admin/deposits/");
	}
	$deposit_row = mysql_fetch_array($deposit_res);
	
	$dp_res = mysql_query("select * from `deposit_percent` where `deposit_id` = '$deposit_id' order by `dp_id`");
	$dp_rub = $dp_usd = $dp_eur = array();
	$i = $j = $k = 0;
	while ($dp_row = mysql_fetch_array($dp_res))
	{
		switch($dp_row['currency'])
		{
			case "RUB": $dp_rub[$i]['period'] = $dp_row['period'];
						$dp_rub[$i]['amount'] = $dp_row['amount'];
						$dp_rub[$i++]['percent'] = $dp_row['percent'];
						break;
			case "USD": $dp_usd[$j]['period'] = $dp_row['period'];
						$dp_usd[$j]['amount'] = $dp_row['amount'];
						$dp_usd[$j++]['percent'] = $dp_row['percent'];
						break;
			case "EUR": $dp_eur[$k]['period'] = $dp_row['period'];
						$dp_eur[$k]['amount'] = $dp_row['amount'];
						$dp_eur[$k++]['percent'] = $dp_row['percent'];
						break;
		}
	}
	if (($rub_count = count($dp_rub)) > 0)
	{
		$rub_period = $rub_amount = array();
		for ($i = 0; $i < $rub_count; $i++)
		{
			if (!in_array($dp_rub[$i]['period'],$rub_period))
				$rub_period[] = $dp_rub[$i]['period'];
			if (!in_array($dp_rub[$i]['amount'],$rub_amount))
				$rub_amount[] = $dp_rub[$i]['amount'];
		}
		$rub_period_count = count($rub_period);
		$rub_amount_count = count($rub_amount);
	}
	if (($usd_count = count($dp_usd)) > 0)
	{
		$usd_period = $usd_amount = array();
		for ($i = 0; $i < $usd_count; $i++)
		{
			if (!in_array($dp_usd[$i]['period'],$usd_period))
				$usd_period[] = $dp_usd[$i]['period'];
			if (!in_array($dp_usd[$i]['amount'],$usd_amount))
				$usd_amount[] = $dp_usd[$i]['amount'];
		}
		$usd_period_count = count($usd_period);
		$usd_amount_count = count($usd_amount);
	}
	if (($eur_count = count($dp_eur)) > 0)
	{
		$eur_period = $eur_amount = array();
		for ($i = 0; $i < $eur_count; $i++)
		{
			if (!in_array($dp_eur[$i]['period'],$eur_period))
				$eur_period[] = $dp_eur[$i]['period'];
			if (!in_array($dp_eur[$i]['amount'],$eur_amount))
				$eur_amount[] = $dp_eur[$i]['amount'];
		}
		$eur_period_count = count($eur_period);
		$eur_amount_count = count($eur_amount);
	}
	
	$city_path = $db->getCell("select `C`.`path` from `city` as `C`,`bank` as `B` where `B`.`bank_id` = '$deposit_row[bank_id]' and `B`.`city_id` = `C`.`city_id` limit 1");
}

require_once ADMIN.HEADFILE;
?>
<style>
.right_line { border-right: 1px #888888 dotted }
.bottom_line { border-bottom: 1px #888888 dotted }
#rub_box input,#usd_box input,#eur_box input { width: 110px; }
.buttons span
{
	cursor: pointer;
	text-decoration: underline;
	line-height: 25px;
}
table hr { height:1px; color:gray; border:0; border-bottom: 1px solid #cccccc; }
</style>
<script type="text/javascript" src="/files/js/admin/deposits.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	<?php
		if ($rub_count == 0) echo "$('#rub').click().change();";
		if ($usd_count == 0) echo "$('#usd').click().change();";
		if ($eur_count == 0) echo "$('#eur').click().change();";
	?>
	$("#bank").change(function(){
		if ($("#bank option:selected").hasClass("branch")) {
			$("#regionally").attr("disabled","disabled").removeAttr("checked");
		} else {
			$("#regionally").removeAttr("disabled");
		}
	})
})
</script>
<div align="left">
<h1>Редактирование вклада</h1>
<hr /><?php
if (isset($_POST['action']) && $_POST['action'] == "edit" && !$edit_error && !$count_error)
	echo "<p style='color:green'>Успешно отредактировано</p>";
elseif ($count_error)
	echo "<p style='color:red'>Необходимо заполнить хотя бы одну таблицу с процентами</p>";
elseif ($edit_error)
	echo "<p style='color:red'>Не удалось отредактировать</p>";
?><form method='POST'>
<input type='hidden' name='action' value='edit' />
<input type='hidden' name='deposit_id' value='<?php echo $deposit_row['deposit_id']; ?>' />
<input type='hidden' name='rub_periods' id='rub_periods' value='<?php echo ($rub_count == 0) ? "1" : $rub_period_count; ?>' />
<input type='hidden' name='rub_amounts' id='rub_amounts' value='<?php echo ($rub_count == 0) ? "1" : $rub_amount_count; ?>' />
<input type='hidden' name='usd_periods' id='usd_periods' value='<?php echo ($usd_count == 0) ? "1" : $usd_period_count; ?>' />
<input type='hidden' name='usd_amounts' id='usd_amounts' value='<?php echo ($usd_count == 0) ? "1" : $usd_amount_count; ?>' />
<input type='hidden' name='eur_periods' id='eur_periods' value='<?php echo ($eur_count == 0) ? "1" : $eur_period_count; ?>' />
<input type='hidden' name='eur_amounts' id='eur_amounts' value='<?php echo ($eur_count == 0) ? "1" : $eur_amount_count; ?>' />
<table cellpadding='5' cellspacing='0'>
	<tr>
		<td width="180px">Ссылка на сайте</td>
		<td width="500px"><a href='<?php echo "/$city_path/deposits/".$deposit_row['deposit_id'];?>' target="_blank"><?php echo $deposit_row['name'];?></a></td>
	</tr>
	<tr>
		<td>ID</td>
		<td><input style="width:200px" type='text' name='deposit_id' value='<?php echo $deposit_row['deposit_id'];?>' disabled /></td>
	</tr>
	<tr>
		<td width="150px">Название</td>
		<td width="500px">
			<input style='width:100%' type='text' name='name' value='<?php echo $deposit_row['name'];?>' />
		</td>
	</tr>
	<tr>
		<td>Банк</td>
		<td>
			<select style="width:200px" name='bank' id='bank'>
				<?php
				$bankslist = $db->getTable("select `bank_id`,`name` from `bank` where `parent` = '0' order by `name`");
				echo "<option disabled='disabled' style='color:gray'>———————————————</option>
						<option disabled='disabled' style='color:gray'>Головные офисы</option>
						<option disabled='disabled' style='color:gray'>———————————————</option>";
				if ($bankslist) {
					
					foreach ($bankslist as $bank) {
						
						echo "<option value='$bank[bank_id]'";
						if ($bank['bank_id'] == $deposit_row['bank_id'])
							echo " selected='selected'";
						echo ">$bank[name]</option>";
					}
				} else {
					echo "<option disabled='disabled' style='color:gray'>В данном городе нет головных офисов</option>";
				}
				$branches = $db->getTable("select `bank_id`,`name` from `bank` where `parent` != '0' and `city_id` = '$_SESSION[city_admin]' order by `name`");
				echo "<option disabled='disabled' style='color:gray'>———————————————</option>
						<option disabled='disabled' style='color:gray'>Филиалы</option>
						<option disabled='disabled' style='color:gray'>———————————————</option>";
				$regional = false;
				if ($branches) {
					
					foreach ($branches as $branch) {
						
						echo "<option class='branch' value='$branch[bank_id]'";
						if ($branch['bank_id'] == $deposit_row['bank_id']) {
							echo " selected='selected'";
							$regional = true;
						}
						echo ">$branch[name]</option>";
					}
				} else {
					echo "<option disabled='disabled' style='color:gray'>В данном городе нет филиалов</option>";
				}
				?>
			</select>
		</td>
	</tr>
	<tr>
		<td>Межрегионально</td>
		<td colspan='2' align="left">
			<input type='checkbox' name='regionally' id='regionally' <?php
				if ($deposit_row['regionally'] == 1) {
					echo "checked='checked'";
				}
				if ($regional) {
					echo "disabled='disabled'";
				}
			?> />
		</td>
	</tr>
	<tr>
		<td>Пополнение</td>
		<td>
			<input type='checkbox' name='increase' <?php if ($deposit_row['increase']) echo "checked='checked'";?> />
		</td>
	</tr>
	<tr>
		<td>Частичное снятие</td>
		<td>
			<input type='checkbox' name='partial_taking' <?php if ($deposit_row['partial_taking']) echo "checked='checked'";?> />
		</td>
	</tr>
	<tr>
		<td>Начисление процентов</td>
		<td>
			<input style='width:100%' type='text' name='procent_charge' value='<?php echo $deposit_row['procent_charge'];?>' />
			<br /><span style='color:gray;font-size:8pt'>Информация через запятую</span>
		</td>
	</tr>
</table>
<table cellpadding='5' cellspacing='0' width="100%" id='boxes'>
	<tr>
		<td colspan='2'><hr /></td>
	</tr>
	<tr>
		<td width="100px" valign='top'><input type='checkbox' name='rub' id='rub' checked="checked" /> RUB</td>
		<td colspan='2' style="border:0px gray solid">
			<table cellpadding="5" cellspacing="0" id="rub_box">
				<tr id="rub_0">
					<td class="bottom_line right_line">Суммы \ Период</td><?php
					if ($rub_count != 0)
					{
						for ($j = 0; $j < $rub_period_count; $j++)
							echo "<td class='bottom_line'><input type='text' name='rub_period_".($j+1)."' value='".$rub_period[$j]."' /></td>";
					}
					else
					{
						?><td class="bottom_line"><input type='text' name='rub_period_1' value="Новый период" /></td><?php
					}
				?></tr><?php
				if ($rub_count != 0)
				{
					for ($i = 0; $i < $rub_amount_count; $i++ )
					{
						echo "<tr id='rub_".($i+1)."'>";
						for ($j = 0; $j <= $rub_period_count; $j++ )
						{
							if ($j == 0)
								echo "<td class='right_line'><input type='text' name='rub_amount_".($i+1)."' value='".$rub_amount[$i]."' /></td>";
							else
								echo "<td><input type='text' name='rub_percent_".$j."_".($i+1)."' value='".$dp_rub[$i*$rub_period_count+$j-1]['percent']."' /></td>";
						}
						echo "</tr>";
					}
				}
				else
				{
					?><tr id="rub_1">
						<td class="right_line"><input type='text' name='rub_amount_1' value="Новая сумма" /></td>
						<td><input type='text' name='rub_percent_1_1' value="Новый процент" /></td>
					</tr><?php
				}
			?></table>
			<div class="buttons">
				<span id="add_rub_period">Добавить период</span> - <span id="del_rub_period">Убрать период</span><br />
				<span id="add_rub_amount">Добавить сумму</span> - <span id="del_rub_amount">Убрать сумму</span>
			</div>
		</td>
	</tr>
	<tr>
		<td colspan='2'><hr /></td>
	</tr>
	<tr>
		<td valign='top'><input type='checkbox' name='usd' id='usd' checked="checked" /> USD</td>
		<td colspan='2' style="border:0px gray solid">
			<table cellpadding="5" cellspacing="0" id="usd_box">
				<tr id="usd_0">
					<td class="bottom_line right_line">Суммы \ Период</td><?php
					if ($usd_count != 0)
					{
						for ($j = 0; $j < $usd_period_count; $j++)
							echo "<td class='bottom_line'><input type='text' name='usd_period_".($j+1)."' value='".$usd_period[$j]."' /></td>";
					}
					else
					{
						?><td class="bottom_line"><input type='text' name='usd_period_1' value="Новый период" /></td><?php
					}
				?></tr><?php
				if ($usd_count != 0)
				{
					for ($i = 0; $i < $usd_amount_count; $i++ )
					{
						echo "<tr id='usd_".($i+1)."'>";
						for ($j = 0; $j <= $usd_period_count; $j++ )
						{
							if ($j == 0)
								echo "<td class='right_line'><input type='text' name='usd_amount_".($i+1)."' value='".$usd_amount[$i]."' /></td>";
							else
								echo "<td><input type='text' name='usd_percent_".$j."_".($i+1)."' value='".$dp_usd[$i*$usd_period_count+$j-1]['percent']."' /></td>";
						}
						echo "</tr>";
					}
				}
				else
				{
					?><tr id="usd_1">
						<td class="right_line"><input type='text' name='usd_amount_1' value="Новая сумма" /></td>
						<td><input type='text' name='usd_percent_1_1' value="Новый процент" /></td>
					</tr><?php
				}
			?></table>
			<div class="buttons">
				<span id="add_usd_period">Добавить период</span> - <span id="del_usd_period">Убрать период</span><br />
				<span id="add_usd_amount">Добавить сумму</span> - <span id="del_usd_amount">Убрать сумму</span>
			</div>
		</td>
	</tr>
	<tr>
		<td colspan='2'><hr /></td>
	</tr>
	<tr>
		<td valign='top'><input type='checkbox' name='eur' id='eur' checked="checked" /> EUR</td>
		<td colspan='2' style="border:0px gray solid">
			<table cellpadding="5" cellspacing="0" id="eur_box">
				<tr id="eur_0">
					<td class="bottom_line right_line">Суммы \ Период</td><?php
					if ($eur_count != 0)
					{
						for ($j = 0; $j < $eur_period_count; $j++)
							echo "<td class='bottom_line'><input type='text' name='eur_period_".($j+1)."' value='".$eur_period[$j]."' /></td>";
					}
					else
					{
						?><td class="bottom_line"><input type='text' name='eur_period_1' value="Новый период" /></td><?php
					}
				?></tr><?php
				if ($eur_count != 0)
				{
					for ($i = 0; $i < $eur_amount_count; $i++ )
					{
						echo "<tr id='eur_".($i+1)."'>";
						for ($j = 0; $j <= $eur_period_count; $j++ )
						{
							if ($j == 0)
								echo "<td class='right_line'><input type='text' name='eur_amount_".($i+1)."' value='".$eur_amount[$i]."' /></td>";
							else
								echo "<td><input type='text' name='eur_percent_".$j."_".($i+1)."' value='".$dp_eur[$i*$eur_period_count+$j-1]['percent']."' /></td>";
						}
						echo "</tr>";
					}
				}
				else
				{
					?><tr id="eur_1">
						<td class="right_line"><input type='text' name='eur_amount_1' value="Новая сумма" /></td>
						<td><input type='text' name='eur_percent_1_1' value="Новый процент" /></td>
					</tr><?php
				}
			?></table>
			<div class="buttons">
				<span id="add_eur_period">Добавить период</span> - <span id="del_eur_period">Убрать период</span><br />
				<span id="add_eur_amount">Добавить сумму</span> - <span id="del_eur_amount">Убрать сумму</span>
			</div>
		</td>
	</tr>
	<tr valign='top'>
		<td colspan='2' align="right"><button style="width:100px;height:30px" type="submit">Сохранить</button></td>
	</tr>
</table>
</form>
<br /><hr /><br />
</div>

<?php require_once ADMIN.FOOTERFILE; ?>